import React from 'react';
import { loadModules } from 'esri-loader';
import {
  ARCGIS_JS_API_URL,
  ARCGIS_PORTAL_URL,
  OPERATION_SERVICE_LAYERS,
  SCENE_LAYERS,
  BASEMAP_REFERENCE_LAYERS,
  D_MAPSERVICE_LAYERS,
  TILED_MAPSERVICE_LAYERS,
  SHC_TILED_MAPSERVICE_LAYERS,
  SHC_D_MAPSERVICE_LAYERS,
  FEATURELAYER_LAYERS
} from '../../common/constants';
import cardStyles from '../../style/card.less';
import tile_json from './tileJson.json';


class EsriMap extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    //初始化地图
    const { mapId, domNode, onZoom, onChangeActiveBasemap } = this.props;
    this.props.onRef(this);
    const that = this;
    const switchButton = document.getElementById('switch-btn');
    const basemapButton = document.getElementById('basemap-btn');
    //将地图存储到window中，做为
    loadModules(
      [
        'esri/config',
        'esri/core/urlUtils',
        'esri/Map',
        'esri/Ground',
        'esri/views/MapView',
        'esri/views/SceneView',
        'esri/WebScene',
        'esri/Basemap',
        'esri/geometry/Extent',
        'esri/geometry/SpatialReference',
        'esri/widgets/BasemapGallery',
        'esri/widgets/Compass',
        'esri/widgets/Expand',
        'esri/layers/TileLayer',
        'esri/layers/FeatureLayer',
        'userPlugins/SHCTiledMapServiceLayer',
        'esri/layers/GraphicsLayer',
        'esri/widgets/LayerList',
        'esri/widgets/Legend',
        'esri/widgets/DirectLineMeasurement3D',
        'esri/widgets/AreaMeasurement3D',
        'esri/identity/IdentityManager',
      ],
      { url: ARCGIS_JS_API_URL }
    )
      .then(
        ([
          esriConfig,
          urlUtils,
          Map,
          Ground,
          MapView,
          SceneView,
          WebScene,
          Basemap,
          Extent,
          SpatialReference,
          BasemapGallery,
          Compass,
          Expand,
          TileLayer,
          FeatureLayer,
          SHCTiledMapServiceLayer,
          GraphicsLayer,
          LayerList,
          Legend,
          DirectLineMeasurement3D,
          AreaMeasurement3D,
          IdentityManager
        ]) => {
          urlUtils.addProxyRule({
            urlPrefix: 'http://map.smi.sh.cegn.cn',
            proxyUrl: 'http://10.108.3.41/DotNet/proxy.ashx'
          })

          const fullExtent = new Extent({
            xmin: -65000,
            ymin: -76000,
            xmax: 75000.00000000003,
            ymax: 72000.00000000003,
            spatialReference: SpatialReference.WebMercator
          })

          window['CSJ_MAP_BASEMAP'] = new Basemap({
            baseLayers: [new TileLayer({
              url: 'http://10.108.3.48/changsanjiao/rest/services/Anse_Map/MapServer',
              fullExtent: fullExtent,
              opacity: 1
            })],
            // baseLayers: [new SHCTiledMapServiceLayer({
            //   url: 'http://map.smi.sh.cegn.cn/OneMapServer/rest/services/shmap_as2/MapServer',
            //   fullExtent: fullExtent,
            //   opacity: 1
            // })],
            referenceLayers: [
              // new TileLayer('http://10.201.37.222/arcgis/rest/services/XHGQ/MapServer')
              // new TileLayer('http://hostserver.xhbd.local/arcgis/rest/services/XH0407GQ/MapServer')
            ],
          });
          window['CSJ_MAP'] = new Map({
            basemap: window['CSJ_MAP_BASEMAP'],
            ground: new Ground({
              surfaceColor: [0, 47, 71],
              // opacity:0.4
            })
          });

          const initCamera = {
            heading: 0,
            tilt: 0.49999999999986244,
            fov: 55,
            position: {
              x: 27121.424705778372,
              y: -31246.07101173337,
              z: 112055.87333349224,
              spatialReference: {
                wkid: 102100
              }
            }
          }

          /* const xhCamera = {
            heading: 0,
            tilt: 49.71801387680861,
            fov: 55,
            position: {
              latitude: -0.24016666517191146,
              longitude: -0.01913645013859481,
              z: 14568.34318894675
            }
          } */

          //MapView SceneView

          window['CSJ_SCENE_VIEW'] = new SceneView({
            container: domNode,
            map: window['CSJ_MAP'],
            viewingMode: 'local',// global
            spatialReference: SpatialReference.WebMercator,
            constraints: {
              rotationEnabled: false, // 仅对map view 生效
            },
            alphaCompositingEnabled: false,
            popup: {
              defaultPopupTemplateEnabled: true
            },
            // qualityProfile: 'high',
            // clippingArea: fullExtent,
            camera: initCamera,
            environment: {
              // atmosphere:null,
              background: {
                type: "color",
                color: [0, 0, 0, 0]
              },
              starsEnabled: false,
              atmosphereEnabled: true,
              lighting: {
                date: new Date("August 1, 2019 9:00:00 GMT +0000"),
                directShadowsEnabled: true,
                ambientOcclusionEnabled: true,
              }
            }
          });
          // 对应图层
          window['CSJ_SCENE_VIEW'].when(function () {
            loadModules(['esri/Basemap', 'esri/layers/MapImageLayer', 'esri/layers/SceneLayer', 'esri/layers/GroupLayer',
              'esri/layers/TileLayer', 'userPlugins/SHCTiledMapServiceLayer', 'userPlugins/SHCDMapImageLayer', 'userPlugins/SHCDTiledMapServiceLayer', 'esri/geometry/Extent', 'esri/tasks/support/LegendLayer', 'esri/geometry/SpatialReference',
            ]).then(([Basemap, MapImageLayer, SceneLayer, GroupLayer, TileLayer, SHCTiledMapServiceLayer, SHCDMapImageLayer, SHCDTiledMapServiceLayer, Extent, LegendLayer, SpatialReference]) => {
              const fullExtent = new Extent({
                xmin: -65000,
                ymin: -76000,
                xmax: 75000.00000000003,
                ymax: 72000.00000000003,
                spatialReference: SpatialReference.WebMercator
              })

              let addToGroupLayer = function (item) {
                switch (item.group) {
                  case 'basemap':
                    window['basemapGroupLayer'].layers.push(window[item.id]);
                    break;
                  case 'landplan873':
                    window['landplan873GroupLayer'].layers.push(window[item.id]);
                    break;
                  case 'building':
                    window['buildingGroupLayer'].layers.push(window[item.id]);
                    break;
                  case 'cityBou':
                    window['cityBouGroupLayer'].layers.push(window[item.id]);
                    break;
                  case 'traffic':
                    window['trafficGroupLayer'].layers.push(window[item.id]);
                    break;
                    case 'LGlabel':
                    window['LGlabelGroupLayer'].layers.push(window[item.id]);
                    break;
                }
              }

              window['basemapGroupLayer'] = new GroupLayer({
                title: '基础底图',
                visible: true,
                // visibilityMode: 'exclusive',
                layers: [],
                opacity: 1,
              })
              window['CSJ_MAP'].add(window['basemapGroupLayer'])

              window['LGlabelGroupLayer'] = new GroupLayer({
                title: '边界标注',
                visible: true,
                layers: [],
                opacity: 1,
              })
              window['CSJ_MAP'].add(window['LGlabelGroupLayer'])

              window['trafficGroupLayer'] = new GroupLayer({
                title: '城市系统',
                visible: true,
                layers: [],
                opacity: 1,
              })
              window['CSJ_MAP'].add(window['trafficGroupLayer'])

              window['cityBouGroupLayer'] = new GroupLayer({
                title: '城市边界',
                visible: true,
                layers: [],
                opacity: 1,
              })
              window['CSJ_MAP'].add(window['cityBouGroupLayer'])

              window['buildingGroupLayer'] = new GroupLayer({
                title: '建筑模型',
                visible: true,
                layers: [],
                opacity: 1,
              })
              window['CSJ_MAP'].add(window['buildingGroupLayer'])

              window['landplan873GroupLayer'] = new GroupLayer({
                title: '规划信息',
                visible: true,
                layers: [],
                opacity: 1,
              })
              window['CSJ_MAP'].add(window['landplan873GroupLayer'])

              SCENE_LAYERS.map(item => {
                window[item.id] =
                  new SceneLayer({
                    title: item.title,
                    id: item.id,
                    popupEnabled:item.popupEnabled,
                    popupTemplate: item.popupTemplate,
                    url: item.url,
                    renderer: item.renderer,
                    legendEnabled: false,
                    definitionExpression: item.definitionExpression,
                    // opacity: 1,
                    elevationInfo: item.elevationInfo,
                    visible: item.visible === true ? true : false,
                  })
                // window['CSJ_MAP'].add(window[item.id])
                addToGroupLayer(item)

              })

              FEATURELAYER_LAYERS.map(item => {
                if (item.renderer) {
                  window[item.id] = new FeatureLayer({
                    title: item.title,
                    popupEnabled: true,
                    id: item.id,
                    url: item.url,
                    opacity: item.opacity ? item.opacity : 1,
                    labelingInfo: item.labelingInfo,
                    elevationInfo: item.elevationInfo?item.elevationInfo:{
                      mode: "absolute-height",
                      offset: 8
                    },
                    hasZ: false,
                    popupEnabled: item.popupEnabled ? true : false,
                    renderer: item.renderer,
                    popupTemplate: item.popupTemplate,
                    visible: item.visible ? item.visible : false,
                    screenSizePerspectiveEnabled: false
                  })
                  addToGroupLayer(item)
                }
                else {
                  window[item.id] = new FeatureLayer({
                    title: item.title,
                    popupEnabled: true,
                    id: item.id,
                    url: item.url,
                    opacity: item.opacity ? item.opacity : 1,
                    elevationInfo: item.elevationInfo?item.elevationInfo:{
                      mode: "absolute-height",
                      offset: 8
                    },
                    hasZ: false,
                    popupEnabled: item.popupEnabled ? true : false,
                    labelingInfo: item.labelingInfo,
                    popupTemplate: item.popupTemplate,
                    visible: item.visible ? item.visible : false,
                    screenSizePerspectiveEnabled: false
                  })
                  addToGroupLayer(item)

                }
                // window['CSJ_MAP'].add(window[item.id])
              })

              D_MAPSERVICE_LAYERS.map(item => {
                window[item.id] = new MapImageLayer({
                  title: item.title,
                  id: item.id,
                  url: item.url,
                  visible: false,
                  legendEnabled: true,
                  popupEnabled: true,
                })
                addToGroupLayer(item)

              })

              SHC_TILED_MAPSERVICE_LAYERS.map(item => {
                window[item.id] =
                  new SHCTiledMapServiceLayer({
                    title: item.title,
                    url: item.url,
                    opacity: 1,
                    fullExtent: fullExtent,
                    visible: item.visible?item.visible:false
                  })
                addToGroupLayer(item)
              })

              TILED_MAPSERVICE_LAYERS.map(item => {
                window[item.id] =
                  new TileLayer({
                    title: item.title,
                    url: item.url,
                    opacity: item.opacity ? item.opacity : 1,
                    fullExtent: fullExtent,
                    visible: item.visible?item.visible:false
                  })
                addToGroupLayer(item)
              })



              // SHC_D_MAPSERVICE_LAYERS.map(item => {
              //   window[item.id] =
              //     new SHCDMapImageLayer({
              //       id: item.id,
              //       title: item.title,
              //       url: item.url,
              //       // tileUrl: tile_json,
              //       tileUrl: 'http://10.108.3.41/arcgis_js_api/library/4.13/dojo/userPlugins/json/tileJson.json',
              //       // tileUrl: 'http://31.0.37.225/arcgis_js_api/library/4.13/dojo/userPlugins/json/tileJson.json',
              //       opacity: 1,
              //       legendEnabled: false,
              //       fullExtent: fullExtent,
              //       visible: false,
              //       // sublayers: item.sublayers,
              //       dLayer: window[item.id]
              //     })
              //   window['CSJ_MAP'].add(window[item.id]);
              //   console.log(item)
              // })

              setTimeout(function () {
                // window['CSJ_SCENE_VIEW'].goTo(xhCamera, {
                //   duration: 2000,
                // })
              }, 2000);




            })

            window['CSJ_SCENE_VIEW'].qualitySettings.memoryLimit = 4096;

            window['ALL_LAYER'] = window['CSJ_MAP'].allLayers;
            window['ALL_LAYER'].map(item => {
              console.log(item.title)
            });

          });

          window['CSJ_SCENE_VIEW_LEGEND'] = new Legend({ view: window['CSJ_SCENE_VIEW'] });

          const layerList = new LayerList({
            view: window['CSJ_SCENE_VIEW'],
          });

          const layerListExpand = new Expand({
            expandTooltip: '专题图层',
            view: window['CSJ_SCENE_VIEW'],
            content: layerList,
          });
          // 暂时移除layerlist

          window['CSJ_LEGEND_EXPAND'] = new Expand({
            expandTooltip: '显示图例',
            expanded: false,
            view: window['CSJ_SCENE_VIEW'],
            content: window['CSJ_SCENE_VIEW_LEGEND'],
          });

          var directLineMeasurement3D, areaMeasurement3D;

          // var directLineMeasurement3D = new DirectLineMeasurement3D({
          //   view: window['CSJ_SCENE_VIEW'],
          // });

          var directLineMeasurement3DExpand = new Expand({
            expandIconClass: 'esri-icon-minus',
            view: window['CSJ_SCENE_VIEW'],
            expandTooltip: '测距',
            // content: directLineMeasurement3D,
          });

          // var bImageMap=fasle;
          switchButton.addEventListener("click", function () {
            var is3D = switchButton.value === "3D";
            if (is3D) {
              switchButton.value = "2D";
              window['CSJ_SCENE_VIEW'].goTo({
                heading: 0,
                tilt: 0,
              }, {
                duration: 2000,
                easing: "in-out-expo"
              });
              window['stop3D'] = window['CSJ_SCENE_VIEW'].on('drag', function (event) {
                if (event.button === 2) {
                  event.stopPropagation();
                }
              })

            } else {
              switchButton.value = "3D";
              window['CSJ_SCENE_VIEW'].goTo({
                heading: 0,
                tilt: 50,
              }, {
                duration: 2000,
                easing: "in-out-expo"
              });
              if (window['stop3D']) {
                window['stop3D'].remove();
              }
            }
          });

          basemapButton.addEventListener("click", function () {
            if (window['AIR_2020'].visible == false) {
              window['AIR_2020'].visible = true
            } else {
              window['AIR_2020'].visible = false
            }
          });

          var areaMeasurement3DExpand = new Expand({
            expandIconClass: 'esri-icon-polygon',
            view: window['CSJ_SCENE_VIEW'],
            expandTooltip: '测面积',
            // content: areaMeasurement3D,
          });

          directLineMeasurement3DExpand.watch('expanded', function (expanded) {
            if (expanded) {
              // window['CSJ_BG_EXPAND'].collapse();
              layerListExpand.collapse();
              areaMeasurement3DExpand.collapse();
              directLineMeasurement3D = new DirectLineMeasurement3D({
                view: window['CSJ_SCENE_VIEW'],
              });
              // only api 4.10
              directLineMeasurement3D.viewModel.newMeasurement();
              directLineMeasurement3DExpand.content = directLineMeasurement3D;
            } else {
              if (directLineMeasurement3D) {
                // directLineMeasurement3D.destroy();
                directLineMeasurement3D.viewModel.clearMeasurement();
                // directLineMeasurement3D=null;
              }
            }
          });

          areaMeasurement3DExpand.watch('expanded', function (expanded) {
            if (expanded) {
              // window['CSJ_BG_EXPAND'].collapse();
              layerListExpand.collapse();
              directLineMeasurement3DExpand.collapse();
              areaMeasurement3D = new AreaMeasurement3D({
                view: window['CSJ_SCENE_VIEW'],
              });
              // 4.9 no newMeasurement()
              areaMeasurement3D.viewModel.newMeasurement();
              areaMeasurement3DExpand.content = areaMeasurement3D;
            } else {
              // areaMeasurement3D.viewModel.clearMeasurement();
              if (areaMeasurement3D) {
                areaMeasurement3D.viewModel.clearMeasurement();
                // areaMeasurement3D.destroy();
                // areaMeasurement3D=null;
              }
            }
          });
          window['CSJ_SCENE_VIEW'].ui.add(window['CSJ_LEGEND_EXPAND'], 'bottom-left');

          window['CSJ_SCENE_VIEW'].ui.remove([
            'zoom',
            'navigation-toggle',
            'attribution',
            'compass',
          ]);

          const compass = new Compass({
            view: window['CSJ_SCENE_VIEW'],
            goToOverride: function () {
              return window['CSJ_SCENE_VIEW'].goTo({
                heading: 0,
                tilt: 0,
              }, {
                duration: 2000,
                easing: "in-out-expo"
              });
            },
          });
          window['CSJ_SCENE_VIEW'].ui.add(layerListExpand, 'top-left');

          window['CSJ_SCENE_VIEW'].ui.add(compass, 'top-left');
          IdentityManager.on('dialog-create', function () {
            IdentityManager.dialog.open = true
          })

          window['GRAPHIC_LAYER_LOCATE'] = new GraphicsLayer({
            listMode: 'hide',
            legendEnabled: false,
            // elevationInfo: {
            //   mode: 'relative-to-ground',
            //   offset: 10,
            //   unit: 'meters',
            // },
          });
          window['CSJ_MAP'].add(window['GRAPHIC_LAYER_LOCATE']);
        }
      )
      .catch(err => {
        console.error(err);
      });
  }



  closeAllOperationServiceLayers() {
    // close OPERATION_SERVICE_LAYERS中的图层
    if (window['ALL_LAYER'] !== undefined && window['ALL_LAYER'].length > 0) {
      window['ALL_LAYER'].map(item => {
        SHC_TILED_MAPSERVICE_LAYERS.map(layerItem => {
          if (item.title === layerItem.title) {
            window[layerItem.id].visible = false;
          }
        })

        SCENE_LAYERS.map(layerItem => {
          if (item.title === layerItem.title) {
            window[layerItem.id].visible = false;
          }
        })

        TILED_MAPSERVICE_LAYERS.map(layerItem => {
          if (item.title === layerItem.title) {
            window[layerItem.id].visible = false;
          }
        })

        FEATURELAYER_LAYERS.map(layerItem => {
          if (item.title === layerItem.title) {
            window[layerItem.id].visible = false;
          }
        })

        //增加用户自定义图层的开关
        if (window['CREATED_GEOJSON_LAYER_IDS'])
          window['CREATED_GEOJSON_LAYER_IDS'].map(layerItemName => {
            if (item.title === layerItemName) {
              window[layerItemName].visible = false;
            }
          })
      });
    }
  }

  closeAllBasemapReferenceLayers() {
    if (window['ALL_LAYER'] !== undefined && window['ALL_LAYER'].length > 0) {
      window['ALL_LAYER'].map(item => {
        if (BASEMAP_REFERENCE_LAYERS[item.title]) {
          window[BASEMAP_REFERENCE_LAYERS[item.title]].visible = false;
        }
      });
    }
  }

  changeUnderground(type) {
    if (type === 1) {
      window['CSJ_MAP'].ground.navigationConstraint = {
        type: 'none'
      }
      window['CSJ_MAP'].ground.surfaceColor = "#fff";
      window['CSJ_MAP'].ground.opacity = 0.2;
    } else {
      window['CSJ_MAP'].ground.opacity = 1;
    }
  }

  changeBaseMapLayer(url, type) {
    loadModules(['esri/Basemap', 'esri/layers/TileLayer', 'userPlugins/SHCTiledMapServiceLayer', 'esri/geometry/Extent', 'esri/geometry/SpatialReference',
    ]).then(([Basemap, TileLayer, SHCTiledMapServiceLayer, Extent, SpatialReference]) => {
      var fullExtent = new Extent({
        xmin: -65000,
        ymin: -76000,
        xmax: 75000.00000000003,
        ymax: 72000.00000000003,
        spatialReference: SpatialReference.WebMercator
      })
      if (type === 1) {
        const basemap = new Basemap({
          baseLayers: [new SHCTiledMapServiceLayer({
            url: url,
            fullExtent: fullExtent,
            opacity: 1
          })],
          referenceLayers: [
            // new TileLayer(...)
          ],
        });
        window['CSJ_MAP'].basemap = basemap;
      } else {
        const basemap = new Basemap({
          baseLayers: [new TileLayer({
            url: url,
            fullExtent: fullExtent,
            opacity: 1
          })],
          referenceLayers: [
            // new TileLayer(...)
          ],
        });
        window['CSJ_MAP'].basemap = basemap;
      }
    });


  }




  render() {
    const { domNode } = this.props;
    // return <div id={domNode} />;
    return <div>
      <div id={domNode} />
      <div id="basemapDiv" >
        <div
          className="esri-component esri-widget--button esri-widget esri-interactive"
        >
          <span id="basemap-btn"
            title="切换底图" className="esri-collapse__icon esri-icon-basemap"></span>
        </div>
      </div>

      <div id="infoDiv" >
        <input
          className="esri-component esri-widget--button esri-widget esri-interactive"
          type="button"
          id="switch-btn"
          value="3D"
        />
      </div>
    </div>;
  }
}

export default EsriMap;
